const SNOW_BEGIN_TIMESTAMP = 1669824000n; //2022-12-01零点时间戳
const SNOW_MAX = 1048576n; //自增最大值

//32位时间戳+12位serverID+20位自增值
class Snowflake {
    constructor(serverID, timeStampBegin=SNOW_BEGIN_TIMESTAMP) {
        this._serverID = BigInt(serverID);
        this._timeStampBegin = BigInt(timeStampBegin);
        this._timeStamp = 0n;
        this._inc = 0n;
    }
    getID() {
        let id = 0n;
        do
        {
            const st = BigInt(parseInt(Date.now()/1000)) - this._timeStampBegin;
            if (st != this._timeStamp)
            {
                this._inc = 0n;
                this._timeStamp = st;
            }
            id = this._timeStamp;
            id <<= 32n;
            id |= (this._serverID << 20n) | this._inc;
            this._inc++;
        } while (this._inc >= SNOW_MAX);

        return id;
    }
    getIDString() {
        return this.getID().toString();
    }
    //解析ID中的时间戳
	static parseTimeStamp(id) {
        const bid = BigInt(id);
        return bid >> 32n;
    }
    //解析ID中的serverID
	static parseServerId(id) {
        const bid = BigInt(id);
        return (bid & 0x00000000ffffffffn) >> 20n;
    }
    //解析ID中自增值
	static parseServerInc(id) {
        const bid = BigInt(id);
        return ((bid << 44n)&0xffffff0000000000n) >> 44n;
    }
}

module.exports = Snowflake;
